<template>
	<div class="app-container">
		<template v-if="flag">
			<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
				<el-form-item label="文章标题" prop="title">
					<el-input
						v-model="queryParams.title"
						placeholder="请输入文章标题"
						clearable
						size="small"
						@keyup.enter.native="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="操作人员" prop="createBy">
					<el-input
						v-model="queryParams.createBy"
						placeholder="请输入操作人员"
						clearable
						size="small"
						@keyup.enter.native="handleQuery"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
					<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>

			<el-row :gutter="10" class="mb8">
				<el-col :span="1.5">
					<el-button
						type="primary"
						icon="el-icon-plus"
						size="mini"
						@click="handleAdd"
					>新增
					</el-button>
				</el-col>
				<el-col :span="1.5">
					<el-button
						type="danger"
						icon="el-icon-delete"
						size="mini"
						:disabled="multiple"
						@click="handleDelete"
					>删除
					</el-button>
				</el-col>
				<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
			</el-row>

			<el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center"/>
				<el-table-column label="序号" align="center" prop="articleId" width="100"/>
				<el-table-column label="文章标题" align="center" :show-overflow-tooltip="true">
					<template slot-scope="scope">
						<el-button type="text" size="mini" @click="downloadFile(scope.row)">{{
								scope.row.title
							}}
						</el-button>
					</template>
				</el-table-column>
				<el-table-column
					label="状态"
					align="center"
					prop="status"
					width="100"
				>
					<template slot-scope="scope">
						{{ scope.row.status == 1 ? "草稿" : "发布" }}
					</template>
				</el-table-column>
				<el-table-column label="创建时间" align="center" prop="createTime" width="100">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template slot-scope="scope">
						<el-button
							size="mini"
							type="text"
							icon="el-icon-delete"
							@click="handleDelete(scope.row)"
						>删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination
				v-show="total>0"
				:total="total"
				:page.sync="queryParams.pageNum"
				:limit.sync="queryParams.pageSize"
				@pagination="getList"
			/>

			<!-- 添加或修改文章对话框 -->
			<el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
				<el-form ref="form" :model="form" :rules="rules" label-width="80px">
					<el-row>
						<el-col :span="24">
							<el-form-item label="上传文件">
								<el-upload ref="upload" :limit="1" accept=".xlsx, .xls, .docx, .doc, .pdf, .ppt, .pptx" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" drag>
									<i class="el-icon-upload"></i>
									<div class="el-upload__text">
										将文件拖到此处，或
										<em>点击上传</em>
									</div>
									<div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”、“xlsx”、“doc”、“docx”、“ppt”、“pptx”、“pdf”格式文件！</div>
								</el-upload>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="文章标题" prop="title">
								<el-input v-model="form.title" style="width: 80%;" placeholder="请输入文章标题"/>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="状态">
								<el-radio-group v-model="form.status">
									<el-radio :label="1">草稿</el-radio>
									<el-radio :label="0">发布</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div slot="footer" class="dialog-footer" style="padding-top:30px">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</el-dialog>
		</template>
		<template v-else>
			<el-page-header @back="goBack" content="详情页面">
			</el-page-header>
			<h1 style="text-align: center">{{ currentRow.title }}</h1>
			<div v-html="currentRow.content" style="padding: 20px 50px 50px 50px;overflow: hidden;"></div>
		</template>
	</div>
</template>

<script>
import {listType} from '@/api/hospital/articleType'
import {listNew, delNew, addNew, updateNew} from "@/api/healthy/new";
import Editor from '@/components/Editor';
import {getToken} from "@/utils/auth";
const OSS = require("ali-oss");
const client = new OSS({
	region: 'oss-cn-beijing',
	accessKeyId: 'LTAI4GJBXeDYFrA5MYK752xh',
	accessKeySecret: '8yKOOnjTweki3oIskUVgpHkZWsJ1AD',
	bucket: 'ycgm-wechat-new'
});

export default {
	components: {
		Editor
	},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 文章表格数据
			noticeList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			//是否弹出文章类型树
			dialogVisible: false,
			//文章类型数据接收
			tableData: [],
			//疾病数据接收
			tableIllData: [],
			// 类型数据字典
			statusOptions: [],
			flag: true,
			currentRow: {},
			defaultProps: {
				children: 'children',
				label: 'label'
			},
			//文章分类 字典字段
			articleClassification: [],
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				title: undefined,
				createBy: undefined,
				status: undefined
			},
			typeId: '',
			deptName: '',
			// 表单参数
			form: {
				articleId: undefined,
				title: undefined,
				content: undefined,
				status: 0,
				thumbnail: undefined,
				fileUrl: undefined
			},
			// 表单校验
			rules: {
				title: [
					{required: true, message: "文章标题不能为空", trigger: "blur"}
				],
				noticeType: [
					{required: true, message: "文章类型不能为空", trigger: "blur"}
				]
			},
			upload: {
				// 是否禁用上传
				isUploading: false,
				// 设置上传的请求头部
				headers: { Authorization: "Bearer " + getToken() },
				// 上传的地址
				url: process.env.VUE_APP_BASE_API + "/uploadOssFile",
			}
		};
	},
	created() {
		this.getList();
		this.getDicts("sys_notice_status").then(response => {
			this.statusOptions = response.data;
		});
	},
	methods: {
		/** 查询文章列表 */
		getList() {
			this.loading = true;
			listNew(this.queryParams).then(response => {
				this.noticeList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 文章状态字典翻译
		statusFormat(row, column) {
			return this.selectDictLabel(this.statusOptions, row.status);
		},
		handleFileUploadProgress(event, file, fileList) {
			this.upload.isUploading = true;
		},
		handleFileSuccess(response, file, fileList) {
			if(response.code == 200) {
				this.form.title = response.originalFilename;
				this.form.fileUrl = response.fileName;
				this.upload.isUploading = false;
			}
		},
		// 取消按钮
		cancel() {
			this.$refs.upload.clearFiles();
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				articleId: undefined,
				title: undefined,
				content: undefined,
				status: 0,
				thumbnail: undefined,
				fileUrl: undefined
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.noticeId)
			this.single = selection.length != 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加文章";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			let articleId = row.articleId || this.ids
			listNew({'articleId': articleId}).then(res => {
				if (res.code === 200) {
					this.reset();
					this.open = true;
					this.title = "修改文章";
					this.form = res.rows[0];
				}
			});
		},
		/** 提交按钮 */
		submitForm: function () {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.articleId != undefined) {
						updateNew(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							}
						});
					} else {
						addNew(this.form).then(response => {
							if (response.code === 200) {
								this.$refs.upload.clearFiles();
								this.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							}
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			let articleId = row.articleId || this.ids
			this.$confirm('是否确认删除文章编号为"' + articleId + '"的数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(function () {
				return delNew(articleId);
			}).then(() => {
				this.getList();
				this.msgSuccess("删除成功");
			}).catch(function () {
			});
		},
		/** 文章类型树 */
		treeType() {
			this.dialogVisible = true;
		},
		setThumbnail(thumbnail) {
			this.form.thumbnail = thumbnail;
		},
		getDeptTypeList() {
			listType().then(res => {
				this.tableData = this.handleTree(res.data, "typeId");
			})
			// GetDeptTypeList(this.params).then(res => {
			//   this.tableData = res.data;
			// });
			this.getDicts("article_classify").then(response => {
				this.articleClassification = response.data;
			});
		},
		downloadFile(row) {
			let extension = row.fileUrl.substring(row.fileUrl.lastIndexOf('.'));
			let url = client.signatureUrl(row.fileUrl, {
				response: {
					"content-disposition": `attachment; filename=${row.title + extension}`
				}
			});
			let a = document.createElement('a')
			a.href = url;
			a.click();
			a.remove();
		}
	}
};
</script>
<style lang="scss" scoped>
.deptInput, .deptBtn {
	float: left;
}

.deptInput {
	width: 200px;
}

.deptBtn {
	margin-left: 10px;
}
</style>
